<template>
  <div>
    <!-- 项目列表表格 -->
    <div v-if="projects.length > 0" class="project-table">
      <el-table :data="projects" style="width: 100%">
        <el-table-column prop="name" label="项目名称" width="180">
          <template #default="{ row }">
            <el-icon>
              <Folder />
            </el-icon>
            <router-link
              :to="{ name: 'participate/:projectName/:projectId', params: { projectId: row.id, projectName: row.name } }"
              class="project-name-link" @click="handleProjectClick(row)">
              {{ row.name }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" width="180">
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" width="180">
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="180">
        </el-table-column>
        <!-- 进度列 -->
        <el-table-column label="进度" width="200">
          <template #default="{ row }">
            <el-progress :percentage="row.projectScheduleVO.progress"
              :color="progressColor(row.projectScheduleVO.progress)"></el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="projectScheduleVO" label="项目进度" width="100">
          <template #default="{ row }">
            {{ row.projectScheduleVO.done }}/{{ row.projectScheduleVO.total }}
          </template>
        </el-table-column>
        <el-table-column prop="creator_name" label="负责人" width="100">
          <template #default="{ row }">
            {{ row.creator_name || '未指定' }}
          </template>
        </el-table-column>
        <el-table-column prop="projectScheduleVO" label="剩余时间" width="100">
          <template #default="{ row }">
            {{ row.projectScheduleVO.remaining }}小时
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="primary" plain @click="viewDetails(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <p v-else>暂无项目记录。</p>

    <!-- 创建项目的按钮 -->
    <el-button @click="openDialog" class="create-project-button">创建项目</el-button>

    <!-- 创建项目的弹窗 -->
    <el-dialog v-model="dialogVisible" title="创建项目" width="50%">
      <el-form :model="projectForm" :rules="rules" ref="projectFormRef" label-width="120px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="projectForm.description"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker type="datetime" placeholder="选择日期时间" v-model="projectForm.start_time"
            style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker type="datetime" placeholder="选择日期时间" v-model="projectForm.end_time"
            style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="创建者" prop="creator_id">
          <el-input v-model="projectForm.creator_name" disabled placeholder="此字段不可编辑"></el-input>
        </el-form-item>
        <el-form-item label="方法模板" prop="method_template_id">
          <el-input v-model="projectForm.method_template_id"></el-input>
        </el-form-item>
        <el-form-item label="成员" prop="members">
          <div>
            <el-tag v-for="member in projectForm.members" :key="member">{{ member }}</el-tag>
            <el-select v-model="projectForm.members" multiple placeholder="请选择成员" style="margin-left: 10px;"
              @focus="fetchEmployees">
              <el-option v-for="employee in employees" :key="employee.id" :label="employee.name" :value="employee.id">
                <span>{{ employee.name }}</span>
              </el-option>
            </el-select>
            <!-- <el-button @click="addMember"  size="small" icon="el-icon-plus" circle></el-button> -->
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查看项目详情的弹窗 -->
    <el-dialog v-model="detailsDialogVisible" title="项目详情" width="60%">
      <pre class="details-pre">{{ details }}</pre>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from '../../api/axios.js'
import { ElMessage } from 'element-plus'
import { useProjectStore } from '../../store/projectStore.js'
import { useCookies } from "vue3-cookies"

const { cookies } = useCookies();
const projectStore = useProjectStore()
const dialogVisible = ref(false)
const projectFormRef = ref(null)
const projects = ref([]) // 存储所有项目的数组
const detailsDialogVisible = ref(false);
const details = ref('');

const projectForm = reactive({
  name: '',
  description: '',
  start_time: null,
  end_time: null,
  creator_id: '',
  creator_name: '', // 新增属性来显示创建者的名字
  method_template_id: '',
  members: []
});

// const selectedEmployee = ref(null);
const employees = ref([]);

const rules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  description: [{ required: false, message: '请输入项目描述', trigger: 'blur' }],
  start_time: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  end_time: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  creator_id: [{ required: true, message: '请选择创建者', trigger: 'blur' }],
  method_template_id: [{ required: true, message: '请选择方法模板', trigger: 'blur' }],
  members: [{ required: true, message: '请选择成员', trigger: 'blur' }]
}

// 获取员工列表
const fetchEmployees = async () => {
  await axios.get('/employee/getEmployeeList')
    .then(response => {
      employees.value = response.data.data || [];
    })
    .catch(error => {
      console.error('Failed to fetch employees:', error);
      ElMessage.error('获取员工列表失败');
    });
};

// 添加成员
const addMember = () => {
  if (selectedEmployee.value && !projectForm.value.members.includes(selectedEmployee.value)) {
    projectForm.value.members.push(selectedEmployee.value);
    selectedEmployee.value = null; // 清空选择
  }
};

function openDialog() {
  dialogVisible.value = true;

  // 获取当前登录用户的 ID 和名字
  const currentUserID = cookies.get("id")
  const currentUserName = cookies.get("name")

  if (currentUserID && currentUserName) {
    projectForm.creator_id = currentUserID;
    projectForm.creator_name = currentUserName;
  }
}

onMounted(async () => {
  try {
    const res = await axios.get('/project/myProject', {
      params: {
        cid: cookies.get("id") // 使用当前用户的ID
      }
    })
    console.log(res);
    // 从响应数据中提取项目列表
    const projectList = res.data.data && res.data.data.list ? res.data.data.list : [];
    // 处理项目列表，并存储在 projects.value 中
    projects.value = projectList.map(project => ({
      id: project.project.id,
      // 直接用于 el-table 的属性
      name: project.project.name,
      description: project.project.description,
      start_time: formatDateTime(project.project.start_time), // 使用格式化后的时间
      end_time: formatDateTime(project.project.end_time), // 使用格式化后的时间
      creator_name: project.creator && project.creator.name || currentUserName,
      // 保存原始数据，方便后续使用
      fullProject: project,
      creator: project.creator,
      members: project.members,
      projectScheduleVO: project.projectScheduleVO
    }));
  } catch (err) {
    console.error(err);
  }
})

const handleProjectClick = (project) => {
  projectStore.setProjects(project)
}
const viewDetails = (row) => {
  // row 已经包含了完整的项目详情信息
  let formattedDetails = '';

  // 格式化项目基本信息
  formattedDetails += `项目名称: ${row.fullProject.project.name}\n`;
  formattedDetails += `描述: ${row.fullProject.project.description}\n`;
  formattedDetails += `创建时间: ${row.fullProject.project.create_time}\n`;
  formattedDetails += `开始时间: ${row.fullProject.project.start_time}\n`;
  formattedDetails += `结束时间: ${row.fullProject.project.end_time}\n`;
  formattedDetails += `已分配权重: ${row.fullProject.project.assign}\n`;
  // 格式化创建者信息
  formattedDetails += `创建者:`;
  formattedDetails += `${row.creator.name}\n`;

  // 格式化成员信息
  formattedDetails += `成员:`;
  row.members.forEach((member, index) => {
    // formattedDetails += `成员${index + 1}:\n`;
    formattedDetails += `${member.name}`;
    if (index !== row.members.length - 1) {
      formattedDetails += `；`;
    }
  });

  // 更新详情变量
  details.value = formattedDetails;

  // 显示对话框
  detailsDialogVisible.value = true;
};

//提交创建项目表单
function submitForm() {
  projectFormRef.value.validate(async valid => {
    if (!valid) return
    try {
      // 转换时间格式
      const convertDate = (date) => {
        if (date) {
          const d = new Date(date);
          return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
        }
        return null;
      };
      const members = projectForm.members;

      const projectDTO = {
        project: {
          name: projectForm.name,
          description: projectForm.description,
          start_time: convertDate(projectForm.start_time),
          end_time: convertDate(projectForm.end_time),
          creator_id: projectForm.creator_id,
          method_template_id: projectForm.method_template_id
        },
        members: members
      }

      const projectResponse = await axios.post('/project/myProject/create', projectDTO)

      ElMessage.success(projectResponse.data.message)
      dialogVisible.value = false // 关闭弹窗

      // 重新加载项目列表
      await fetchProjects()
      // 清空表单
      resetForm();
    } catch (error) {
      console.error('创建项目失败:', error.response.data);
      ElMessage.error('创建项目失败，请检查输入信息和权限');
    }
  })
}

// 格式化时间为 "YYYY-MM-DD HH:mm"
function formatDateTime(dateTimeString) {
  // 解析时间字符串
  const date = new Date(dateTimeString.replace(' ', 'T') + 'Z');

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

//查看项目
async function fetchProjects() {
  try {
    const res = await axios.get('/project/myProject', {
      params: {
        cid: cookies.get("id") // 使用当前用户的ID
      }
    });
    console.log(res);
    const projectList = res.data.data && res.data.data.list ? res.data.data.list : [];
    projects.value = projectList.map(project => ({
      id: project.project.id,
      // 直接用于 el-table 的属性
      name: project.project.name,
      description: project.project.description,
      start_time: formatDateTime(project.project.start_time), // 使用格式化后的时间
      end_time: formatDateTime(project.project.end_time), // 使用格式化后的时间
      creator_name: project.creator && project.creator.name || currentUserName,
      // 保存原始数据，方便后续使用
      fullProject: project,
      creator: project.creator,
      members: project.members,
      projectScheduleVO: project.projectScheduleVO
    }));
  } catch (err) {
    console.error(err);
  }
}

// 根据进度百分比返回不同的颜色
const progressColor = (progress) => {
  if (progress >= 100) return '#67C23A'; // 完成
  else if (progress >= 50) return '#E6A23C'; // 进行中
  else return '#F56C6C'; // 未开始或延迟
};

function resetForm() {
  if (projectFormRef.value) {
    projectFormRef.value.resetFields();
  }
  // 清空成员数组
  projectForm.members = [];
}
</script>


<style scoped>
.el-container {
  height: 100%;
  box-shadow: 0 0 4px rgb(92, 91, 91);
}

.el-dialog__header {
  background-color: #f9fafb;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 20px;
  text-align: right;
}

.el-dialog__title {
  color: #4a5568;
}

form.el-form.el-form--default.el-form--label-right.demo-ruleForm {
  margin-top: 8px;
  margin-right: 10px;
}

button.el-button.el-button--primary,
button.el-button {
  width: 10%;
  border-radius: 10px;
}



/* 添加创建项目的按钮样式 */
.create-project-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

/* 查看项目详情的弹窗样式 */
.details-pre {
  white-space: pre-wrap;
  word-break: break-all;
  font-family: "Arial", sans-serif;
  font-size: 14px;
  line-height: 1.5;
  color: #4a5568;
  background-color: #f9fafb;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.project-card {
  margin-bottom: 20px;
}

.project-table {
  margin-bottom: 20px;
}

.el-table {
  border: 1px solid #ddd;
  margin-bottom: 20px;
}

.el-table th,
.el-table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: center;
}

.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.create-project-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

/* 新增样式：项目名称链接 */
.project-name-link {
  display: inline-block;
  color: #4a90e2;
  /* 链接颜色 */
  text-decoration: none;
  /* 去掉下划线 */
  cursor: pointer;
  /* 鼠标悬停样式 */
  font-weight: bold;
  /* 加粗字体 */
}

.project-name-link:hover {
  color: #2c73d2;
  /* 鼠标悬停时的颜色变化 */
  text-decoration: underline;
  /* 鼠标悬停时显示下划线 */
}
</style>